<template>
  <div style="padding: 6px">
    <!-- 添加或修改通用物模型对话框 -->
    <el-dialog draggable title="添加参数" v-model="dialog1.visible" width="1000px" append-to-body
      @close="dialog1.visible = false">
      <div style="margin: -30px 0 30px; background-color: #ddd; height: 1px"></div>
      <el-row>
        <el-col :span="12" style="border: 1px solid #ddd; border-radius: 5px; padding: 10px; background-color: #eee">
          <el-form :inline="true" label-width="48px">
            <el-form-item label="" prop="templateName">
              <el-input placeholder="请输入物模型名称" style="width: 150px" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="info" icon="search" @click="handleQuery" style="padding: 5px">搜索</el-button>
            </el-form-item>
            <el-form-item>
              <el-link :underline="false" icon="InfoFilled" type="primary" style="margin-left: 10px">单击应用模板</el-link>
            </el-form-item>
          </el-form>

          <el-table :data="thingsModelTemplateList" highlight-current-row :border="false" :show-header="false"
            :row-style="{ backgroundColor: '#eee' }" @row-click="handleRowClick">
            <el-table-column #default="scope" label="选择" width="30" align="center">
              <input :checked="scope.row.selected" type="radio" name="template" style="margin-top: 8px;" />
            </el-table-column>
            <el-table-column label="名称" align="left" prop="templateName" />
            <el-table-column label="标识符" align="left" prop="identifier" />
            <el-table-column label="数据类型" align="center" prop="datatype" width="60">
              <template #default="scope">
                <dict-tag :options="iot_data_type" :value="scope.row.datatype" />
              </template>
            </el-table-column>
          </el-table>
          <pagination small v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            :total="total" style="margin: 0 0 10px;
             background-color: #eee" layout="prev, pager, next" @pagination="getList" />

        </el-col>

        <el-col :span="11" :offset="1">
          <el-form ref="form" label-width="80px">
            <el-form-item label="参数名称" prop="templateName">
              <el-input v-model="formData.templateName" placeholder="例如：温度" style="width: 270px" />
            </el-form-item>
            <el-form-item label="参数标识" prop="id">
              <el-input v-model="formData.identifier" placeholder="例如：temperature" style="width: 270px"></el-input>
            </el-form-item>
            <el-form-item label="参数排序" prop="order">
              <el-input-number v-model="formData.modelOrder" controls-position="right" placeholder="请输入排序" type="number"
                style="width: 180px" />
            </el-form-item>

            <el-form-item label="参数特性" prop="property">
              <el-checkbox v-model="formData.isChart" name="isChart" label="图表展示" :true-label="1"
                :false-label="0"></el-checkbox>
              <el-checkbox v-model="formData.isMonitor" name="isMonitor" label="实时监测" :true-label="1"
                :false-label="0"></el-checkbox>
              <el-checkbox v-model="formData.isReadonly" name="isReadonly" label="只读数据" :true-label="1"
                :false-label="0"></el-checkbox>
              <el-checkbox v-model="formData.isHistory" name="isHistory" label="历史存储" :true-label="1"
                :false-label="0"></el-checkbox>
              <el-checkbox v-model="formData.isSharePerm" name="isSharePerm" label="分享权限" :true-label="1"
                :false-label="0"></el-checkbox>
            </el-form-item>

            <div style="margin-bottom: 20px; background-color: #ddd; height: 1px"></div>
            <el-form-item label="数据类型" prop="datatype">
              <el-select v-model="formData.datatype" placeholder="请选择数据类型" style="width: 125px">
                <el-option v-for="dict in iot_data_type" :key="dict.value" :label="dict.label" :value="dict.value"
                  :disabled="dict.value === '5' || dict.value === '7'" />
              </el-select>
            </el-form-item>
            <div v-if="formData.datatype == '1' || formData.datatype == '2'">
              <el-form-item label="取值范围">
                <el-row>
                  <el-col :span="10">
                    <el-input v-model="specs.min" placeholder="最小值" type="number" />
                  </el-col>
                  <el-col :span="4" align="center">到</el-col>
                  <el-col :span="10">
                    <el-input v-model="specs.max" placeholder="最大值" type="number" />
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="单位">
                <el-input v-model="specs.unit" placeholder="例如：℃" style="width: 308px" />
              </el-form-item>
              <el-form-item label="步长">
                <el-input-number v-model="specs.step" controls-position="right" placeholder="例如：1" type="number"
                  style="width: 308px" />
              </el-form-item>
            </div>
            <div v-if="formData.datatype == '4'">
              <el-form-item label="布尔值" prop="">
                <el-row style="margin-bottom: 10px">
                  <el-col :span="10">
                    <el-input v-model="specs.falseText" placeholder="例如：关闭" />
                  </el-col>
                  <el-col :span="10" :offset="1">（0 值对应文本）</el-col>
                </el-row>
                <el-row>
                  <el-col :span="10">
                    <el-input v-model="specs.trueText" placeholder="例如：打开" />
                  </el-col>
                  <el-col :span="10" :offset="1">（1 值对应文本）</el-col>
                </el-row>
              </el-form-item>
            </div>
            <div v-if="formData.datatype == '6'">
              <el-form-item label="展示方式">
                <el-select v-model="specs.showWay" placeholder="请选择展示方式" style="width: 175px">
                  <el-option key="select" label="下拉框" value="select"></el-option>
                  <el-option key="button" label="按钮" value="button"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="枚举项" prop="">
                <el-row v-for="(item, index) in specs.enumList" :key="'enum' + index" style="margin-bottom: 10px">
                  <el-col :span="8">
                    <el-input v-model="item.value" placeholder="例如：0" />
                  </el-col>
                  <el-col :span="11" :offset="1">
                    <el-input v-model="item.text" placeholder="例如：中速挡位" />
                  </el-col>
                  <el-col :span="3" :offset="1" v-if="index != 0" @click="removeEnumItem(index)"><a
                      style="color: #f56c6c">删除</a></el-col>
                </el-row>
                <div>
                  +
                  <a style="color: #409eff" @click="addEnumItem()">添加枚举项</a>
                </div>
              </el-form-item>
            </div>
            <div v-if="formData.datatype == '3'">
              <el-form-item label="最大长度" prop="">
                <el-row>
                  <el-col :span="10">
                    <el-input placeholder="例如：1024" type="number" style="width: 150px;" />
                  </el-col>
                </el-row>
              </el-form-item>
            </div>
          </el-form>

        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4" :offset="20">
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-col>
      </el-row>


    </el-dialog>
  </div>
</template>

<style scoped>
.specsColor {
  background-color: #fcfcfc;
}
</style>

<script setup lang="ts">
import { listThingsModelTemplate, getThingsModelTemplate, delThingsModelTemplate, addThingsModelTemplate, updateThingsModelTemplate } from '@/api/iot/thingsModelTemplate';
import { ThingsModelTemplateVO, ThingsModelTemplateQuery, ThingsModelTemplateForm, specs } from '@/api/iot/thingsModelTemplate/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_data_type } = toRefs<any>(proxy?.useDict('iot_data_type', 'iot_type', 'iot_yes_no'));
const loading = ref(true);
const thingsModelTemplateList = ref<ThingsModelTemplateVO[]>([]);
const total = ref(0);
const dialog1 = reactive({
  visible: false,
  title: '添加参数'
});

const reformData: any = reactive({
  parameter: {},
  index: -1
});
const specs: specs = reactive({
  min: 0,
  max: 0,
  unit: '',
  step: undefined,
  type: undefined,
  falseText: '',
  trueText: '',
  showWay: 'select',
  maxLength: '1024',
  arrayCount: 5,
  arrayType: 1,
  params: [],
  enumList: [{ value: undefined, text: undefined }]
});
const formData = reactive<ThingsModelTemplateForm>({
  templateId: undefined,
  templateName: undefined,
  identifier: undefined,
  type: 1,
  datatype: '1',
  specs: undefined,
  isChart: 1,
  isMonitor: 1,
  isHistory: 1,
  isReadonly: 1,
  isSharePerm: 1,
  modelOrder: 0,
});
const data = reactive<PageData<ThingsModelTemplateForm, ThingsModelTemplateQuery>>({
  form: { ...formData },
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    templateName: undefined,
    identifier: undefined,
    type: undefined,
    params: {
    }
  },
  rules: {
    templateId: [
      { required: true, message: "物模型ID不能为空", trigger: "blur" }
    ],
    templateName: [
      { required: true, message: "物模型名称不能为空", trigger: "blur" }
    ],
    identifier: [
      { required: true, message: "标识符，产品下唯一不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "模型类别不能为空", trigger: "change" }
    ],
    datatype: [
      { required: true, message: "数据类型不能为空", trigger: "change" }
    ],
    isChart: [
      { required: true, message: "是否图表展示不能为空", trigger: "blur" }
    ],
    isMonitor: [
      { required: true, message: "是否实时监测不能为空", trigger: "blur" }
    ],
    isHistory: [
      { required: true, message: "是否历史存储 (0-否，1-是）不能为空", trigger: "blur" }
    ],
  }
});

defineExpose({
  dialog1,
  reformData
})
const { queryParams, form, rules } = toRefs(data);
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 查询物模型模板列表 */
const getList = async () => {
  loading.value = true;
  const res = await listThingsModelTemplate(queryParams.value);
  thingsModelTemplateList.value = res.rows;
  thingsModelTemplateList.value.forEach(item => {
    item.selected = false;
  });
  total.value = res.total;
  loading.value = false;

}
/** 删除枚举项 */
const removeEnumItem = (index) => {
  specs.enumList.splice(index, 1);
}
/**监听visible变化 */
watch(
  () => dialog1.visible,
  (newVal) => {
    if (newVal) {
      console.log('dialog1.visible', newVal);
      // 当 dialog1.visible 变为 true 时，初始化列表
      reset();
      getList();
    }
  }
);
/** 添加枚举项 */
const addEnumItem = () => {
  console.log('addEnumItem');
  specs.enumList.push({
    value: '',
    text: '',
  });
};
/**列表点击事件*/
const handleRowClick = (item1: ThingsModelTemplateVO) => {
  console.log('handleRowClick');
  console.log(item1);

  thingsModelTemplateList.value.forEach(item => {

    if (item.templateId == item1.templateId) {
      console.log('item1=', item1.templateName);
      item.selected = true;
      formData.templateId=item1.templateId;
      formData.templateName = item1.templateName;
      formData.identifier = item1.identifier;
      formData.type = item1.type;
      formData.datatype = item1.datatype;
      formData.modelOrder = item1.modelOrder;
      formData.isChart = item1.isChart;
      formData.isMonitor = item1.isMonitor;
      formData.isHistory = item1.isHistory;
      formData.isReadonly = item1.isReadonly;
      formData.isSharePerm = item1.isSharePerm;
      //字符串转json
      const specsStr = typeof item1.specs === 'string' ? item1.specs : JSON.stringify(item1.specs);
      const specs1 = JSON.parse(specsStr);
      specs.min = specs1.min;
      specs.max = specs1.max;
      specs.unit = specs1.unit;
      specs.step = Number(specs1.step);
      specs.type = specs1.type;
      specs.falseText = specs1.falseText;
      specs.trueText = specs1.trueText;
      specs.showWay = specs1.showWay;
      specs.maxLength = specs1.maxLength;
      specs.arrayCount = specs1.arrayCount;
      specs.arrayType = specs1.arrayType;
      specs.params = specs1.params;
    } else {
      item.selected = false;
    }

  });
}
// 取消按钮
const cancel = () => {
  dialog1.visible = false;
  reset();
};
// 表单重置
const reset = () => {
  //  index = -1;
  formData.templateId = undefined;
  formData.templateName = undefined;
  formData.identifier = undefined;
  formData.type = 1;
  formData.datatype = '1';
  formData.specs = undefined;
  formData.isChart = 1;
  formData.isMonitor = 1;
  formData.isHistory = 1;
  formData.isReadonly = 1;
  formData.isSharePerm = 1;
  formData.modelOrder = 0;
}

const submitForm = () => {

  // 格式化datatype
  formData.datatype = formatThingsSpecs();
  // 清空不需要存储数据
  delete formData.specs;

  // 返回参数对象

  reformData.parameter = JSON.parse(JSON.stringify(formData));
  console.log('reformData', reformData);
  dialog1.visible = false;
}

// 格式化物模型
const formatThingsSpecs = () => {
  console.log('formatThingsSpecs');
  var data: any = {};
  data.type = formData.datatype;
  if (formData.datatype == '1' || formData.datatype == '2') {
    data.min = Number(specs.min ? specs.min : 0);
    data.max = Number(specs.max ? specs.max : 100);
    data.unit = specs.unit ? specs.unit : '';
    data.step = Number(specs.step ? specs.step : 1);
  } else if (formData.datatype == '3') {
    data.maxLength = Number(specs.maxLength ? specs.maxLength : 1024);
  } else if (formData.datatype == '4') {
    data.falseText = specs.falseText ? specs.falseText : '关闭';
    data.trueText = specs.trueText ? specs.trueText : '打开';
  } else if (formData.datatype == '5') {
    data.arrayType = specs.arrayType;
  } else if (formData.datatype == '6') {
    data.showWay = specs.showWay;
    if (specs.enumList && specs.enumList[0].text != '') {
      data.enumList = specs.enumList;
    } else {
      data.showWay = 'select';
      data.enumList = [
        {
          value: '0',
          text: '低',
        },
        {
          value: '1',
          text: '高',
        },
      ];
    }
  }
  return data;
}
</script>
